package com.kd.crawler.common.utils;

import java.io.IOException;
import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public final class IJedisPool {

	private static JedisPool jedisPool;
	// 静态代码初始化池配置
	static {
		try {
			Properties props = new Properties();
			props.load(IJedisPool.class.getClassLoader().getResourceAsStream("redis.properties"));
			// 创建jedis池配置实例
			JedisPoolConfig config = new JedisPoolConfig();
			// 设置池配置项值
			config.setMaxTotal(Integer.valueOf(props.getProperty("jedis.pool.maxActive")));
			config.setMaxIdle(Integer.valueOf(props.getProperty("jedis.pool.maxIdle")));
			config.setMaxWaitMillis(Long.valueOf(props.getProperty("jedis.pool.maxWait")));
			config.setTestOnBorrow(Boolean.valueOf(props.getProperty("jedis.pool.testOnBorrow")));
			config.setTestOnReturn(Boolean.valueOf(props.getProperty("jedis.pool.testOnReturn")));
			System.out.println(props.getProperty("redis.ip"));
			// 根据配置实例化jedis池
			jedisPool = new JedisPool(config, props.getProperty("redis.ip"),Integer.valueOf(props.getProperty("redis.port")),30000, props.getProperty("redis.passowrd"));
			

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/** 获得jedis对象 */
	private static Jedis getJedis() {
		return jedisPool.getResource();

	}
	
	public static String get(String key){
		Jedis jedis=getJedis();
		String value=jedis.get(key);
		returnResource(jedis);
		return value;
	}
	
	public static void set(String key,String value){
		Jedis jedis=getJedis();
		jedis.set(key, value);
		returnResource(jedis);
	}
	
	public static long sadd(String key,String value){
		Jedis jedis=getJedis();
		long l=jedis.sadd(key, value);
		returnResource(jedis);
		return l;
	}
	
	/**
	 * 释放jedis资源
	 * 
	 * @param jedis
	 */
	public static void returnResource(final Jedis jedis) {
		if (jedis != null) {
			jedisPool.returnResource(jedis);
		}
	}
	
	public static void main(String[] args) {
		System.out.println(IJedisPool.sadd("KD_CRAWL_URL_MD5_SET", "20"));
//		System.out.println(IJedisPool.get("KD_CRAWL_URL_MD5_SET"));
	}
	
	
}
